<template>
  <div class="purchase-order-page">
    <n-grid :cols="24">
      <n-grid-item span="24">
        <detail-page-header title="采购回收订单详情">
          <n-button type="primary" class="flex items-center">
            <span>支付</span>
          </n-button>
          <n-button @click.stop="handleChangeOrderStatus"
            >切换状态测试</n-button
          >
        </detail-page-header>
        <div class="mt-[16px]"></div>
        <n-grid :col="24" x-gap="10">
          <n-grid-item span="14">
            <n-card>
              <n-h3>
                <span class="mr-2">#{{ purchaseInfo.num }}</span>
                <DictTag
                  v-if="purchaseInfo.status"
                  dict="pos_purchase_status"
                  :value="purchaseInfo.status"
                />
              </n-h3>
              <div class="flex items-center">
                <n-icon><TimeOutline /></n-icon>
                <span class="ml-1">
                  创建时间：{{ purchaseInfo.createTime }}
                </span>
              </div>
              <div class="mt-[16px]"></div>
              <n-card size="small">
                <div class="mb-2">
                  <span class="font-bold text-base">回收设备清单</span>
                </div>
                <!-- ITEMS -->
                <div
                  class="purchase-item"
                  v-for="item in purchaseItems"
                  :key="item.id"
                >
                  <div class="flex">
                    <div class="flex-1 flex justify-between mr-10">
                      <span>{{ item.variantName }}</span>
                      <span>{{ item.quantity }}</span>
                    </div>
                    <div class="text-right">
                      <span>{{ currencyFormat(item.rowTotal) }}</span>
                    </div>
                  </div>
                  <div
                    class="flex justify-between items-center mt-1"
                    v-for="sn in item.snName"
                    :key="sn"
                  >
                    <div>
                      <span>序列号/IMEI：</span>
                      <span>{{ sn }}</span>
                    </div>
                  </div>
                </div>

                <template #action>
                  <div class="flex justify-between">
                    <span class="font-bold text-base">订单总金额：</span>
                    <span class="font-bold text-base">
                      {{ currencyFormat(purchaseInfo.total) }}
                    </span>
                  </div>
                </template>
              </n-card>
              <!-- NOTES -->
              <div class="mt-[16px]">
                <div class="mb-2">
                  <span class="font-bold text-base">备注：</span>
                </div>
                <n-spin :show="getPurchaseNotesLoading">
                  <template v-if="purchaseNotesList.length">
                    <div
                      class="note-item"
                      v-for="note in purchaseNotesList"
                      :key="note.id"
                    >
                      <div class="content">
                        <span>{{ note.message }}</span>
                      </div>
                      <div class="create-time">
                        <span>{{ note.createTime }}</span>
                      </div>
                    </div>
                  </template>
                  <n-empty v-else> </n-empty>
                </n-spin>
                <div class="mt-2">
                  <n-input
                    v-model:value="createPurchaseNoteForm.note"
                    type="textarea"
                    placeholder="请输入备注信息"
                  />
                </div>
                <div class="mt-2 text-right">
                  <n-button
                    :disabled="!createPurchaseNoteForm.note"
                    @click.stop="handleAddNote"
                    :loading="getPurchaseNotesLoading"
                    >保存备注</n-button
                  >
                </div>
              </div>
            </n-card>
          </n-grid-item>
          <n-grid-item span="10">
            <n-card>
              <n-h3>供应商信息</n-h3>
              <div class="mt-[16px]">
                <n-grid :cols="24" :x-gap="10" :y-gap="10">
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><Person /></n-icon><span class="ml-1">姓名</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ supplierInfo.name }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><PhonePortraitOutline /></n-icon
                      ><span class="ml-1">联系电话</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ supplierInfo.phoneNumber }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><Mail /></n-icon><span class="ml-1">邮箱</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ supplierInfo.email || "/" }}</span>
                    </div>
                  </n-grid-item>
                </n-grid>
              </div>
            </n-card>
            <div class="mt-[10px]"></div>
            <n-card>
              <n-h3>支付信息</n-h3>
              <div class="mb-2 flex justify-between items-center">
                <span class="font-bold text-base">已支付金额：</span>
                <span class="font-bold">
                  {{ currencyFormat(purchaseInfo.paidAmount) }}
                </span>
              </div>
              <!-- PAYMENT ITEM -->
              <div
                class="payment-item"
                v-for="item in paymentsList"
                :key="item.id"
              >
                <div>
                  <div class="desc">
                    <span>支付订单编号：</span>
                    <span class="payment-num">#{{ item.id }}</span>
                  </div>
                  <div class="amount">
                    <span>
                      {{ getPaymentMethodName(item.method) }} -
                      {{ currencyFormat(item.amount) }}
                    </span>
                  </div>
                  <div class="desc mt-1">
                    <span>{{ item.createTime }}</span>
                  </div>
                </div>
                <div>
                  <img
                    class="w-[48px]"
                    :src="getPaymentAsset(`${item.method}.png`)"
                  />
                </div>
              </div>
            </n-card>
          </n-grid-item>
        </n-grid>
      </n-grid-item>
    </n-grid>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { debounce, get } from "lodash-es";
import Big from "big.js";
import {
  TimeOutline,
  List,
  Person,
  PhonePortraitOutline,
  Mail,
} from "@vicons/ionicons5";
import { addTradeInPayment } from "@/api/purchase/purchase.api";
import {
  getPurchaseOrderDetail,
  changePurchaseOrderStatus,
  completeOrder,
} from "@/api/purchase/purchase.api";

import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { DictStorage } from "@/storage/dict.storage";
import {
  useCheckResultModal,
  CheckResultModal,
} from "@/components/biz/checkResultModal/index.ts";
import {
  usePaymentModal,
  PaymentModal,
} from "@/components/biz/paymentModal/index.ts";
import {
  getPaymentAsset,
  getPaymentMethodName,
} from "@/common/utils/payment/index";
import DictTag from "@/components/biz/dictTag/index.vue";
import { IPurchaseOrderDetailProps } from "./props";
import { useNote } from "../../tradeIn/detail/hooks/useNote.ts";

const props = defineProps<IPurchaseOrderDetailProps>();

const paymentMethods = DictStorage.getDictItemsByCode(
  "pos_tradein_payment_method"
);

const {
  modalShowFlag: showPayment,
  handleShowModal: handleShowPaymentModal,
  handleHideModal: handleHidePaymentModal,
} = usePaymentModal();

const {
  createPurchaseNoteForm,
  getPurchaseNotesLoading,
  purchaseNotesList,
  handleAddTradeInNote,
  handleGetPurchaseNotes,
} = useNote();

const paymentConfirmLoading = ref<boolean>(false);

const orderDetail = ref<any>({});

const canAddPayment = computed<boolean>(() => {
  const status = get(orderDetail.value, "posPurchase.status");
  return status === "unpaid";
});

const dueAmount = computed(() => {
  const total = get(orderDetail.value, "posPurchase.total") || 0;
  const paidAmount = get(orderDetail.value, "posPurchase.paidAmount") || 0;
  return new Big(total).minus(paidAmount).toNumber();
});

const purchaseInfo = computed(() => {
  return get(orderDetail.value, "posPurchase") || {};
});

const purchaseItems = computed(() => {
  return get(orderDetail.value, "items") || [];
});

const supplierInfo = computed(() => {
  return get(orderDetail.value, "supplier") || {};
});

const paymentsList = computed(() => {
  return get(orderDetail.value, "payments") || [];
});

const handleAddNote = debounce(function () {
  handleAddTradeInNote(props.id);
}, 200);

const handleHidePayment = () => {
  if (!paymentConfirmLoading.value) {
    handleHidePaymentModal();
  }
};

const handleConfirmAddPayment = debounce(async function (
  paymentMethods: any[]
) {
  const purchaseId = get(orderDetail.value, "posPurchase.id") || "";
  if (!purchaseId) {
    return;
  }
  const params = {
    purchaseId,
    paymentItems: paymentMethods.map((item) => {
      return {
        method: item.paymentMethod,
        amount: item.amount,
      };
    }),
  };
  const result = await addTradeInPayment(params);
  console.log(result);
});

const handleGetOrderDetail = async (orderId: string) => {
  const result = await getPurchaseOrderDetail(orderId);
  console.log(result);
  orderDetail.value = result.result;
};

const handleClickkAddPayment = () => {
  handleShowPaymentModal();
};

const handleChangeOrderStatus = async () => {
  completeOrder(props.id);
};

onMounted(() => {
  handleGetOrderDetail(props.id);
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
